<!-- Good be like is a Requirement Statistics Project table -->
<template>
  <ContainerLayout class="requirement-statistics">
    <div class="form-container">
      <el-form ref="formRef" :inline="true" :model="queryForm" class="query-form" label-width="40px">
        <el-form-item>
          <el-radio-group v-model="showType" @change="handleChangeShowType">
            <el-radio-button v-for="item in tableTypeList" :key="item.value" :label="item.label" v-bind:value="item.value" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户" v-if="false">
          <el-input v-model="queryForm.user" clearable placeholder="请输入" style="width: 100px" />
        </el-form-item>
        <el-form-item label="部门">
          <el-cascader :options="deptList" :props="deptProps" style="width: 290px" v-model="queryForm.deptIds" collapse-tags clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="queryForm.timelogCategory" placeholder="选择" style="width: 80px">
            <el-option label="全部" value="" />
            <el-option v-for="item in projectTypes" :key="item.dictCode" :label="item.dictLabel" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" v-if="queryForm.timelogCategory === '0'">
          <el-select v-model="projectValue" placeholder="请选择项目" style="width: 180px" :max-collapse-tags="1" multiple clearable collapse-tags>
            <template #header>
              <el-checkbox v-model="checkAllProject" :indeterminate="indeterminateProject" @change="handleCheckAllProject">全部</el-checkbox>
            </template>
            <el-option v-for="item in projectList" :key="item.code" :label="`${item.code}-${item.cname}`" :value="item.id" />
          </el-select>
        </el-form-item>
        <TimeSlotDatePicker label="时段" v-model="queryForm.date" />
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button @click="handleClickBtnReset" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container" ref="tableContainer">
      <el-scrollbar :height="scrollbarHeight">
        <template v-if="isQueryed">
          <template v-if="tableDatas.length">
            <div v-for="(tableData, idx) in tableDatas" class="table-cells" :style="styleTableCells">
              <div class="table-title">{{ tableData.tableTitle }}{{ tableHeight }}</div>
              <div class="table-wrap" ref="tableWrap">
                <el-table :data="tableData.result" scrollbar-always-on style="width: 100%" border :summary-method="(ev:any) => getSummaries(idx, ev)" show-summary :height="tableHeight" header-cell-class-name="table-header-row" empty-text="没有数据">
                  <el-table-column label="部门" width="150" fixed>
                    <template #default="scope">
                      <div>{{ scope.row.deptName }}({{ scope.row.deptUserLength }})</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="total" label="Total" width="100" fixed>
                    <template #default="scope">
                      {{ showTableColumnTotal(scope.row, idx) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="任务名" width="90" fixed>
                    <template #default="scope">{{ scope.row.taskName }} </template>
                  </el-table-column>
                  <el-table-column label="任务类型" width="90" fixed>
                    <template #default="scope">{{ scope.row.taskCategory }} </template>
                  </el-table-column>
                  <el-table-column v-for="item in tableColumnDate" :prop="item.label" width="80" resizable>
                    <template #header>
                      <div class="table-header-cell">
                        <div>{{ item.label }}</div>
                        <!-- <div>{{ item.end }}</div> -->
                      </div>
                    </template>
                    <template #default="scope">
                      {{ scope.row[item.columnName + ':val'] }}
                    </template>
                  </el-table-column>
                  <el-table-column />
                </el-table>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="table-title" v-if="projectTitle !== ''">{{ projectTitle }}</div>
            <el-empty description="没有查询到符合条件的数据" />
          </template>
        </template>
        <template v-else>
          <el-empty description="尚未查询数据" />
        </template>
      </el-scrollbar>
    </div>
  </ContainerLayout>
</template>
<script setup lang="ts">
import ContainerLayout from '../layout/ContainerLayout.vue'
// import type { VNode } from 'vue'
import { reactive, ref, onMounted, h, nextTick, computed, watch } from 'vue'
import { useDeptStore, useProjectssStore, useTaskTypeStore, useUsersStore, useFormSearchDataStore } from '../stores'
import IProjectTypes from '../interface/IProjectTypes'
import { Refresh, Search } from '@element-plus/icons-vue'
// import { ElMessage } from 'element-plus'
import type { CheckboxValueType } from 'element-plus'
import http from '../http'
import * as utils from '../utils'
// import { useRouter, useRoute } from 'vue-router'
import TimeSlotDatePicker from '../layout/FormTableLayout/TimeSlotDatePicker.vue'
import Api from '../api'

const isDev = ref(true)
if (import.meta.env.VITE_APP_ENV === 'production') {
  isDev.value = false
}
const deptCountMap = ref<any>({})
// 工作时长
const workingHours = ref(0)
const deptStore = useDeptStore()
const projectssStore = useProjectssStore()
const tableWrap = ref<HTMLElement[]>([])
const tableHeight = ref<any>(null)
const tableContainer = ref(ref<HTMLElement | null>(null))
const scrollbarHeight = ref(400)
const styleTableCells = ref({})
// 多选
const checkAllProject = ref(false)
const indeterminateProject = ref(false)
const projectValue = ref<CheckboxValueType[]>([])
// 表单
const queryForm = reactive({
  user: '',
  projectId: '',
  date: [] as Date[],
  deptIds: [] as string[] | number[],
  timelogCategory: '',
})
const deptProps = ref({ multiple: true, label: 'deptName', value: 'deptId' })
const deptList = ref(deptStore.getAllState())
const projectTypes = ref<IProjectTypes[]>(useTaskTypeStore().getAllState())
const projectList = ref<Array<{ id: number; code: string; cname: string }>>(projectssStore.getAllState() as any)
// 显示类型 0: 人/周 1: 人/天
const showType = ref(0)
const tableDatas = ref<any[]>([])
const tableColumnDate = ref<any[]>([])
const rowsTotalCol = ref<any[]>([])
const rowTotalheadcount = ref<any[]>([])
const rowsColHeadcount = ref<any[]>([])
const projectTitle = ref<string>('')
const isQueryed = ref(false)

watch(projectValue, (val: any) => {
  if (val.length === 0) {
    checkAllProject.value = false
    indeterminateProject.value = false
  } else if (val.length === projectList.value.length) {
    checkAllProject.value = true
    indeterminateProject.value = false
  } else {
    indeterminateProject.value = true
  }
})
/**
 * 处理全选项目的逻辑
 *
 * @param val Checkbox 的值
 */
const handleCheckAllProject = (val: CheckboxValueType) => {
  indeterminateProject.value = false
  if (val) {
    projectValue.value = projectList.value.map((_) => _.id)
  } else {
    projectValue.value = []
  }
}

/**
 * 异步获取数据
 *
 * @param startTimelogDate 开始时间
 * @param endTimelogDate 结束时间
 * @returns 返回数据行
 */
const fetchDataRowTotalByPath = async (startTimelogDate: any, endTimelogDate: any, path: string) => {
  projectTitle.value = `${startTimelogDate} - ${endTimelogDate} ${currentShowTypeItem.value.label} 统计`
  const params = {
    startTimelogDate,
    endTimelogDate,
  }
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  if (showType.value == 1 && queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }
  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  const tableTitles: any = []
  const requestParams = []
  if (queryForm.timelogCategory === '0' && projectValue.value.length > 0) {
    projectValue.value.forEach((e: any) => {
      // projectList.value
      const project = projectList.value.find((pe) => pe.id === e)
      if (project) {
        tableTitles.push(`${project.code}-${project.cname}`)
      }

      requestParams.push(
        http({
          method: 'GET',
          path,
          params: { ...params, projectId: e },
        })
      )
    })
  } else {
    requestParams.push(
      http({
        method: 'GET',
        path,
        params,
      })
    )
  }
  // console.log('requestParams', requestParams)
  const ress = await Promise.all(requestParams)
  const resList = []
  if (tableTitles.length > 0) {
    for (let i = 0; i < ress.length; i++) {
      resList.push({
        tableTitle: tableTitles[i],
        dataList: ress[i],
      })
    }
  } else {
    resList.push({
      tableTitle: projectTitle.value,
      dataList: ress[0],
    })
  }

  return resList
}
/**
 * 异步获取数据
 *
 * @param startTimelogDate 开始时间
 * @param endTimelogDate 结束时间
 * @returns 返回数据行
 */
const fetchData = async (startTimelogDate: any, endTimelogDate: any) => {
  projectTitle.value = `${startTimelogDate} - ${endTimelogDate} ${currentShowTypeItem.value.label} 统计`
  const params = {
    startTimelogDate,
    endTimelogDate,
  }
  const deptIds: any[] = []
  queryForm.deptIds.forEach((e: any) => {
    deptIds.push(e[e.length - 1])
  })
  if (deptIds.length > 0) {
    Object.assign(params, { deptIds: deptIds.join(',') })
  }
  if (showType.value == 1 && queryForm.user !== '') {
    Object.assign(params, { userName: queryForm.user })
  }
  if (queryForm.timelogCategory !== '') {
    Object.assign(params, { timelogCategory: queryForm.timelogCategory })
  }
  const tableTitles: any = []
  const requestParams = []
  if (queryForm.timelogCategory === '0' && projectValue.value.length > 0) {
    projectValue.value.forEach((e: any) => {
      // projectList.value
      const project = projectList.value.find((pe) => pe.id === e)
      if (project) {
        tableTitles.push(`${project.code}-${project.cname}`)
      }

      requestParams.push(
        http({
          method: 'GET',
          path: currentShowTypeItem.value.path,
          params: { ...params, projectId: e },
        })
      )
    })
  } else {
    requestParams.push(
      http({
        method: 'GET',
        path: currentShowTypeItem.value.path,
        params,
      })
    )
  }
  // console.log('requestParams', requestParams)
  const ress = await Promise.all(requestParams)
  const resList = []
  if (tableTitles.length > 0) {
    for (let i = 0; i < ress.length; i++) {
      resList.push({
        tableTitle: tableTitles[i],
        dataList: ress[i],
      })
    }
  } else {
    resList.push({
      tableTitle: projectTitle.value,
      dataList: ress[0],
    })
  }

  return resList
}
const showTableColumnTotal = (val: any, index: number) => {
  // console.log('rowsTotalCol.value[index].dataList.rows', rowsTotalCol.value[index].dataList.rows)
  // console.log('index', index)
  // console.log('val', val)

  if (val) {
    let item: any = rowsTotalCol.value[index].dataList.rows.find((e: any) => e.deptId === val.deptId)
    if (item) {
      return item.durationTime
    }
  }
}
/**
 * 获取部门周统计数据
 *
 * 此函数用于请求部门的周统计数据，可以帮助管理人员了解部门在一周内的工作量、进度或其他关键指标
 * 该函数目前未实现具体逻辑，需要根据后端接口文档添加请求代码
 */
const getDepartmentWeeklyStats = async () => {
  tableDatas.value = []
  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date

    if (currentShowTypeItem.value) {
      const weeks = utils.getWeeksBetweenDates2(start, end)
      // console.log('start', utils.formatDate(new Date(start), 'yyyy-MM-dd'))
      // const [first] = weeks
      // const [last] = weeks.slice(-1)
      let startTimelogDate = utils.formatDate(new Date(start), 'yyyy-MM-dd')
      let endTimelogDate = utils.formatDate(new Date(end), 'yyyy-MM-dd')
      console.log('startTimelogDate', startTimelogDate)
      // 设置 table 列
      tableColumnDate.value = [
        ...weeks.map((e) => {
          const start2 = utils.formatDate(e.start, 'yyyy-MM-dd')
          const end2 = utils.formatDate(e.end, 'yyyy-MM-dd')
          const startYear = utils.formatDate(e.start, 'yyyy')
          const endYear = utils.formatDate(e.end, 'yyyy')
          const startDay = utils.formatDate(e.start, 'MM-dd')
          const endDay = utils.formatDate(e.end, 'MM-dd')
          return { label: start2, columnName: `${start2} - ${end2}`, start2, end2, startDay, endDay, startYear, endYear }
        }),
      ]
      // tableTitle
      // dataList
      const resList = await fetchData(startTimelogDate, endTimelogDate)
      rowsTotalCol.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listtotal')
      // 合计 单元格
      rowTotalheadcount.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listusertotalheadcount')
      // 合计 总百分比
      rowsColHeadcount.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listheadcount')

      tableDatas.value = []
      resList.forEach((item: any) => {
        const result: any = {}
        const tableTitle = item.tableTitle
        const { rows } = item.dataList
        // console.log('tableTitle', tableTitle)
        rows.forEach((row: any) => {
          const key = `${row.deptId}`
          if (!result[key]) {
            result[key] = {
              deptId: row.deptId,
              deptName: row.deptName,
              workDurationTime: row.workDurationTime,
              total: 0,
              totalOld: 0,
            }
          }
          const dateRange = `${row.weekStartDate} - ${row.weekEndDate}`
          if (!result[key][dateRange]) {
            result[key][dateRange] = row.durationTime
          } else {
            result[key][dateRange] += row.durationTime
          }
          result[key].total += row.durationTime
          result[key].totalOld += row.durationTime
        })
        for (const key in result) {
          const e = result[key]
          // 当前行工时
          // const workDurationTime = e.workDurationTime
          for (let index = 0; index < tableColumnDate.value.length; index++) {
            const temp = tableColumnDate.value[index]
            if (!e[temp.columnName]) {
              // console.log('e[temp.columnName] 未定义', e, temp)
              e[temp.columnName] = 0
            }
            // (每周工作时长 [ 为取整 × 1000 ] )
            // 每周工作时长 / minutes 每天工作时长 （长春 400 分钟）/ 5 一周 5 天 [ 为还原 ÷ 1000 ]
            const colVal = e[temp.columnName] // (e[temp.columnName] * 1000) / workDurationTime / currentShowTypeItem.value.days

            e[temp.columnName] = colVal
            e[temp.start] = e[temp.columnName]
            e[temp.columnName + ':val'] = colVal // utils.formatNumber(colVal / 1000)
          }
          // (每周总工作时长 [ 为取整 × 1000 ] )
          // 每周总工作时长 / minutes 每天工作时长 （长春 400 分钟）/ 5 一周 5 天 [ 为还原 ÷ 1000 ]
          const totalVal = e.total // (e.total * 1000) / workDurationTime / currentShowTypeItem.value.days
          e.total = totalVal
          e['total:val'] = totalVal //utils.formatNumber(totalVal / 1000)
        }
        const tempResult = Object.values(result)
        tempResult.map(async (e: any) => {
          e.deptUserLength = deptCountMap.value[e.deptId]
        })
        tableDatas.value.push({
          tableTitle,
          result: tempResult,
        })
      })

      // const rows: any[] = []
      // tableData.value = Object.values(result)
      nextTick(() => {
        if (tableContainer.value) {
          scrollbarHeight.value = tableContainer.value.offsetHeight
        }
        styleTableCells.value = {}
        tableHeight.value = 'auto'
        if (tableDatas.value.length === 1) {
          styleTableCells.value = { height: `${scrollbarHeight.value}px` }
          nextTick(() => {
            if (tableWrap.value) {
              // tableHeight.value = tableWrap.value[0].offsetHeight
              tableHeight.value = scrollbarHeight.value - 40
            }
          })
        }
      })
    }
  }
}

/**
 * 获取部门每日统计数据
 *
 * 该函数用于请求并获取部门级别的每日统计数据这通常包括部门的人数、出勤情况、工作量等信息
 * 统计数据可以帮助管理层了解部门的运营状况和效率，以便做出相应的决策和调整
 *
 */
const getDepartmentDailyStats = async () => {
  tableDatas.value = []
  if (queryForm.date.length == 2) {
    const [start, end] = queryForm.date
    const startTimelogDate = utils.formatDate(new Date(start), 'yyyy-MM-dd')
    const endTimelogDate = utils.formatDate(new Date(end), 'yyyy-MM-dd')
    const days = utils.generateDates(start, end)
    // const showTypeItem = tableTypeList.value[showType.value]

    if (currentShowTypeItem.value) {
      // 设置 table 列
      tableColumnDate.value = [
        ...days.map((e) => {
          return { label: e, columnName: e, start: e }
        }),
      ]
      const resList = await fetchData(startTimelogDate, endTimelogDate)
      rowsTotalCol.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listtotal')
      // 合计 单元格
      rowTotalheadcount.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listusertotalheadcount')
      // 合计 总百分比
      rowsColHeadcount.value = await fetchDataRowTotalByPath(startTimelogDate, endTimelogDate, '/dev-api/oa/timelog/listheadcountday')

      tableDatas.value = []
      resList.forEach((item: any) => {
        const result: any = {}
        const tableTitle = item.tableTitle
        const { rows } = item.dataList
        rows.forEach((row: any) => {
          const key = `${row.deptId}`
          if (!result[key]) {
            result[key] = {
              deptId: row.deptId,
              deptName: row.deptName,
              workDurationTime: row.workDurationTime,
              total: 0,
              totalOld: 0,
            }
          }
          // const dateRange = `${row.weekStartDate} - ${row.weekEndDate}`
          if (!result[key][row.timelogDate]) {
            result[key][row.timelogDate] = row.durationTime
          } else {
            result[key][row.timelogDate] += row.durationTime
          }
          result[key].total += row.durationTime
          result[key].totalOld += row.durationTime
          // result[row.deptId][row.timelogDate].total = row.durationTime + result[row.deptId][row.timelogDate].total
        })

        for (const key in result) {
          const e = result[key]
          // 当前行工时
          // const workDurationTime = e.workDurationTime
          for (let index = 0; index < tableColumnDate.value.length; index++) {
            const temp = tableColumnDate.value[index]
            if (!e[temp.columnName]) {
              e[temp.columnName] = 0
            }
            e[temp.start] = e[temp.columnName]
            // (每周工作时长 [ 为取整 × 1000 ] )
            // 每周工作时长 / minutes 每天工作时长 （长春 400 分钟）/ 1 天 [ 为还原 ÷ 1000 ]
            const colVal = e[temp.columnName] //(e[temp.columnName] * 1000) / workDurationTime / currentShowTypeItem.value.days
            e[temp.columnName] = colVal
            e[temp.start] = e[temp.columnName]
            e[temp.columnName + ':val'] = colVal // utils.formatNumber(colVal / 1000)
          }
          // (每周总工作时长 [ 为取整 × 1000 ] )
          // 每周总工作时长 / minutes 每天工作时长 （长春 400 分钟）/ 1 天 [ 为还原 ÷ 1000 ]
          const totalVal = e.total // (e.total * 1000) / workDurationTime / currentShowTypeItem.value.days
          e.total = totalVal
          e['total:val'] = totalVal // utils.formatNumber(totalVal / 1000)
        }

        const tempResult = Object.values(result)
        tempResult.map(async (e: any) => {
          e.deptUserLength = deptCountMap.value[e.deptId]
        })
        tableDatas.value.push({
          tableTitle,
          result: tempResult,
        })
      })
      // nextTick(() => {
      //   if (tableWrap.value) {
      //     tableHeight.value = tableWrap.value[0].offsetHeight
      //   }
      // })
      nextTick(() => {
        if (tableContainer.value) {
          scrollbarHeight.value = tableContainer.value.offsetHeight
        }
        styleTableCells.value = {}
        tableHeight.value = 'auto'
        if (tableDatas.value.length === 1) {
          styleTableCells.value = { height: `${scrollbarHeight.value}px` }
          nextTick(() => {
            if (tableWrap.value) {
              tableHeight.value = tableWrap.value[0].offsetHeight
            }
          })
        }
      })
    }
  }
}

const tableTypeList = ref([
  { label: '周', value: 0, days: 5, path: '/dev-api/oa/timelog/listbyweek', queryMethod: getDepartmentWeeklyStats },
  { label: '天', value: 1, days: 1, path: '/dev-api/oa/timelog/listbyday', queryMethod: getDepartmentDailyStats },
])

/**
 * 切换显示类型
 *
 * @param index 显示类型的索引
 * @returns {void}
 */
const currentShowTypeItem = computed(() => tableTypeList.value[showType.value])
/**
 * 异步函数，用于处理表格滚动条事件
 */
const tableScroll = async () => {
  nextTick(() => {
    // 表格滚动条事件
    const scrollbar = document.querySelectorAll('.table-wrap .el-table__body-wrapper .el-scrollbar__wrap')

    // 如果存在多个滚动条
    if (scrollbar.length > 1) {
      // 遍历每个滚动条
      scrollbar.forEach((tbl, idx) => {
        // 为每个滚动条添加滚动事件监听器
        tbl.addEventListener('scroll', (event: any) => {
          // 获取事件目标
          const target = event.target
          // 遍历所有滚动条
          for (let index = 0; index < scrollbar.length; index++) {
            // 如果当前滚动条不是目标滚动条
            if (index != idx) {
              // 获取当前滚动条元素
              const element = scrollbar[index]
              // 设置当前滚动条的滚动位置为目标滚动条的滚动位置
              element.scrollLeft = target.scrollLeft
            }
          }
        })
      })
    }
  })
}
/**
 * 提交表单处理函数
 *
 * @returns {Promise<void>} 返回一个异步操作的Promise对象，无返回值
 */
const onSubmit = async () => {
  // console.log('queryForm', queryForm)
  isQueryed.value = true
  tableDatas.value = []
  projectTitle.value = ''
  useFormSearchDataStore().setAllState({
    startDate: utils.formatDate(new Date(queryForm.date[0]), 'yyyy-MM-dd'),
    endDate: utils.formatDate(new Date(queryForm.date[1]), 'yyyy-MM-dd'),
  })
  if (queryForm.date.length == 2) {
    await tableTypeList.value[showType.value].queryMethod()
  }
  if (isDev.value) {
    await tableScroll()
  }
}

/**
 * 重置按钮点击事件处理函数
 *
 * @returns 无返回值
 */
const handleClickBtnReset = async () => {
  await resetForm()
  await onSubmit()
}
/**
 * 计算表格数据中的汇总信息
 *
 * @param param 包含表格列信息和数据的对象
 * @returns 返回汇总信息的数组，每个元素可能是字符串或VNode，表示该列的汇总结果
 */
const getSummaries = (idx: number, param: any) => {
  const { columns } = param
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { class: '', style: { height: '40px', lineHeight: '40px' } }, ['Total Headcount'])

      return
    }
    if (index === 1) {
      const { rows, total } = rowTotalheadcount.value[idx].dataList
      if (total === 1) {
        // console.log('rows', )
        // sums[index] = rows[0].durationTime
        sums[index] = h('div', { style: {} }, [rows[0].durationTime])
      } else {
        sums[index] = ''
      }
      return
    }
    // const values = data.map((item: any) => Number(item[column.property]))
    const item = rowsColHeadcount.value[idx].dataList.rows

    if (column.property) {
      // const val = item.find((item: any) => item.weekStartDate === column.property)
      let val: any = null
      if (showType.value === 1) {
        val = item.find((item: any) => item.timelogDate === column.property)
      } else if (showType.value === 0) {
        val = item.find((item: any) => item.weekStartDate === column.property)
      }

      sums[index] = val ? val.durationTime : '0'
    } else {
      sums[index] = ''
    }
  })
  // 去掉第一列和最后一列的汇总信息，第一列是部门名称，最后一列是占位，不需要计算
  for (let index = 1; index < sums.length - 1; index++) {
    sums[index] = sums[index] // utils.formatNumber((sums[index] as number) / 1000)
  }
  // console.log(' ====== ', new Date().getTime())
  // console.log('data', data)
  // console.log('sums', sums)
  return sums
}

/**
 * 重置表单
 *
 * 重置查询表单的所有字段到初始状态，包括用户、项目ID、日期范围、部门 ID 数组和时间日志类别
 */
const resetForm = () => {
  projectValue.value = []
  isQueryed.value = false
  tableDatas.value = []
  projectTitle.value = ''
  const [start, end] = utils.getDateRangeByDate2(utils.shortcutsType.本月) as Date[]
  queryForm.user = ''
  queryForm.projectId = ''
  queryForm.date = [start, end]
  const formSearchData = useFormSearchDataStore().getAllState()
  // console.log('formSearchData', formSearchData)
  if (formSearchData) {
    queryForm.date = [formSearchData.startDate, formSearchData.endDate]
  }
  queryForm.deptIds = [] as string[] | number[]
  queryForm.timelogCategory = ''
}
/**
 * 处理显示类型改变的方法
 *
 * @async
 */
const handleChangeShowType = async () => {
  // await resetForm()
  onSubmit()
}
onMounted(async () => {
  deptCountMap.value = await Api.Dept.getDeptUserCountMap()
  const { minutes } = useUsersStore().getAllState() as any // 获取每天工作时长
  workingHours.value = minutes

  await resetForm()
  // await onSubmit()
})
</script>
<style lang="scss" scoped>
.requirement-statistics {
  display: flex;
  flex-direction: column;
  .form-container {
    display: flex;
    justify-content: flex-start;
  }
  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    .table-wrap {
      flex: 1;
    }
    .table-cells {
      display: flex;
      flex-direction: column;
      & + .table-cells {
        margin-top: 20px;
      }
    }
  }
}
.table-header-cell {
  writing-mode: vertical-lr;
  // line-height: 1;
}
</style>
